package com.youpai.platform.biggod.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youpai.platform.biggod.service.convert.BigGodConverter;
import com.youpai.platform.biggod.service.entity.po.BigGodPO;
import com.youpai.platform.biggod.service.entity.po.SkillPO;
import com.youpai.platform.biggod.service.enums.CategoryEnum;
import com.youpai.platform.biggod.service.enums.SkillExamineStatus;
import com.youpai.platform.biggod.service.mapper.BigGodMapper;
import com.youpai.platform.biggod.service.mapper.SkillMapper;
import com.youpai.platform.biggod.web.entity.req.*;
import com.youpai.platform.chat.service.entity.po.ChatAccountPO;
import com.youpai.platform.chat.service.mapper.ChatAccountMapper;
import com.youpai.platform.common.enums.ProcessCodeEnum;
import com.youpai.platform.common.exceptions.BaseBizException;
import com.youpai.platform.common.util.StringUtils;
import com.youpai.platform.common.util.id.IdGenerator;
import com.youpai.platform.biggod.service.entity.po.SkillExaminePO;
import com.youpai.platform.biggod.service.mapper.SkillExamineMapper;
import com.youpai.platform.biggod.service.service.SkillExamineService;
import com.youpai.platform.biggod.web.entity.dto.SkillExamineDto;
import com.youpai.platform.biggod.web.entity.resp.SkillExamineResp;
import com.youpai.platform.user.service.entity.po.UserPO;
import com.youpai.platform.user.service.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @time: 2022/11/13
 * @author: huanghao
 * @description: 技能审核service实现类
 */
@Slf4j
@Service
public class SkillExamineImpl implements SkillExamineService {

    @Resource
    private SkillExamineMapper skillExamineMapper;

    @Resource
    private SkillMapper skillMapper;

    @Resource
    private BigGodMapper bigGodMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ChatAccountMapper chatAccountMapper;

    @Override
    public SkillExamineResp createSkillExamine(SkillExamineAddReq req) {
        //判断用户是否存在
        LambdaQueryWrapper<UserPO> userFollowPOQueryWrapper = new LambdaQueryWrapper<>();
        userFollowPOQueryWrapper
                .eq(UserPO::getUid, Long.valueOf(req.getUid()));
        UserPO userPO = userMapper.selectOne(userFollowPOQueryWrapper);
        if(userPO == null){
            log.error("用户不存在!");
            throw new BaseBizException(ProcessCodeEnum.USER_NOT_EXIST);
        }
        if(req.getScreenshot() == null){
            log.error("图片不能为空!");
            throw new BaseBizException(ProcessCodeEnum.SCREENSHOT_ISNULL);
        }
        Long categoryId = getCategory(req.getSkill());
        checkExamine(req.getUid(), categoryId);
        Long skillExamineId = IdGenerator.generateId();
        SkillExaminePO skillExaminePO = new SkillExaminePO(
                Long.valueOf(req.getUid()), skillExamineId, categoryId, req.getSkill(),
                req.getRank(), req.getStyle(), req.getPosition(), Double.valueOf(req.getPrice()),
                req.getScreenshot(), 0);
        boolean flag = skillExamineMapper.add(skillExaminePO) > 0;
        if(flag){
            return new SkillExamineResp().setHintText("新增技能审核成功!");
        }else {
            log.error("新增技能审核失败!");
            throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_ADD_EXCEPTION);
        }
    }

    @Override
    public SkillExamineResp updateSkillExamine(SkillExamineUpdateReq req) {
        SkillExaminePO skillExaminePO = skillExamineMapper.get(Long.valueOf(req.getExamineId()));
        if(skillExaminePO == null){
            log.error("当前技能审核不存在!");
            throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_NOT_REPETITION);
        }
        if(skillExaminePO.getExamineStatus() == 1){
            log.error("当前技能审核已通过，无需重复审核!");
            throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_REPEAT);
        }
        skillExaminePO.setRank(req.getRank());
        skillExaminePO.setStyle(req.getStyle());
        skillExaminePO.setPosition(req.getPosition());
        if(StringUtils.isNotEmpty(req.getPrice())) {
            skillExaminePO.setUnitPrice(Double.valueOf(req.getPrice()));
        }
        skillExaminePO.setScreenshot(req.getScreenshot());
        boolean flag = skillExamineMapper.update(skillExaminePO) > 0;
        if(flag){
            return new SkillExamineResp().setHintText("修改技能审核信息成功!");
        }else {
            log.error("修改技能审核信息失败");
            throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_UPDATE_EXCEPTION);
        }
    }

    @Override
    public SkillExamineDto getSkillExamine(SkillExamineGetReq req) {
        SkillExaminePO skillExaminePO = checkSkillExamine(req.getExamineId());
        return BigGodConverter.convertSkillExaminePOToSkillExamineDTO(skillExaminePO, null, null);
    }

    @Override
    public List<SkillExamineDto> getSkillExamineList(SkillExamineListReq req) {
        //默认获取前100条
        Long uid = null;
        if(StringUtils.isNotEmpty(req.getUid())){
            uid = Long.valueOf(req.getUid());
        }
        String skill = null;
        if(StringUtils.isNotEmpty(req.getSkill())){
            skill = req.getSkill();
        }
        List<SkillExaminePO> skillExaminePOS = skillExamineMapper.getSkillExamines(
                req.getExamineStatus(), uid, skill,0, 100);
        List<Long> uids = skillExaminePOS.stream().map(SkillExaminePO::getGodUid).collect(Collectors.toList());
        List<UserPO> userPOS = userMapper.getUsersByUids(uids);
        Map<Long, UserPO> userPOMap = userPOS.stream()
                .collect(Collectors.toMap(UserPO::getUid, Function.identity()));
        List<ChatAccountPO> chatAccountPOS = chatAccountMapper.getChatAccountPOsByUidList(uids);
        Map<String, String> ChatAccountPOMap = chatAccountPOS.stream()
                .collect(Collectors.toMap(ChatAccountPO::getUid, ChatAccountPO::getAccId));
        if(skillExaminePOS.size() > 0){
            return BigGodConverter.convertSkillExaminePOToSkillExamineDTO(skillExaminePOS, userPOMap, ChatAccountPOMap);
        }else {
            return Collections.emptyList();
        }
    }

    @Override
    public SkillExamineResp removeSkillExamine(SkillExamineRemoveReq req) {
        SkillExaminePO skillExaminePO = checkSkillExamine(req.getExamineId());
        List<Long> ids = Collections.singletonList(skillExaminePO.getSkillExamineId());
        boolean flag = skillExamineMapper.remove(ids) > 0;
        if(flag){
            return new SkillExamineResp().setHintText("删除技能审核信息成功!");
        }else {
            log.error("删除技能审核信息失败!");
            throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_REMOVE_EXCEPTION);
        }
    }

    @Override
    public SkillExamineResp examineSkill(SkillExamineReq req) {
        if(req.getExamineStatus() == null){
            req.setExamineStatus(1);
        }
        SkillExaminePO skillExaminePO = checkSkillExamine(req.getExamineId());
        if(req.getExamineStatus().equals(SkillExamineStatus.PASS.getType())){
            //如果通过改审核
            skillExaminePO.setExamineStatus(1);
            boolean flag = skillExamineMapper.update(skillExaminePO) > 0;
            if(flag){
                //审核成功才会新增技能和大神
                createSkill(skillExaminePO);
                return new SkillExamineResp().setHintText("技能审核通过!");
            }else {
                log.error("技能审核失败!");
                throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_FAILED);
            }
        }else {
            skillExaminePO.setExamineStatus(2);
            boolean flag = skillExamineMapper.update(skillExaminePO) > 0;
            if(flag){
                //审核成功才会新增技能和大神
                return new SkillExamineResp().setHintText("成功拒绝该技能审核!");
            }else {
                log.error("技能审核失败!");
                throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_FAILED);
            }
        }
    }

    private void createSkill(SkillExaminePO skillExaminePO) {
        checkSkill(skillExaminePO);
        SkillPO skillPO = new SkillPO();
        Long skillId = IdGenerator.generateId();
        skillPO.setSkillId(skillId);
        skillPO.setGodUid(skillExaminePO.getGodUid());
        skillPO.setCategoryId(skillExaminePO.getCategoryId());
        skillPO.setSkill(skillExaminePO.getSkill());
        skillPO.setRank(skillExaminePO.getRank());
        skillPO.setStyle(skillExaminePO.getStyle());
        skillPO.setPosition(skillExaminePO.getPosition());
        skillPO.setScreenshot(skillExaminePO.getScreenshot());
        skillPO.setUnitPrice(skillExaminePO.getUnitPrice());
        skillPO.setValidStatus(0);
        boolean flag = skillMapper.add(skillPO) > 0;
        if(!flag){
            log.error("新增技能失败");
            throw new BaseBizException(ProcessCodeEnum.SKILL_ADD_EXCEPTION);
        }
        Long godUid = skillExaminePO.getGodUid();
        BigGodPO bigGodPO = bigGodMapper.get(godUid);
        if(bigGodPO == null){
            bigGodPO = new BigGodPO();
            bigGodPO.setUid(godUid);
            LambdaQueryWrapper<UserPO> userFollowPOQueryWrapper = new LambdaQueryWrapper<>();
            userFollowPOQueryWrapper
                    .eq(UserPO::getUid, godUid);
            UserPO userPO = userMapper.selectOne(userFollowPOQueryWrapper);
            bigGodPO.setBigGodNickName(userPO.getNickName());
            boolean flagGod = bigGodMapper.add(bigGodPO) > 0;
            if(!flagGod){
                log.error("新增大神失败");
                throw new BaseBizException(ProcessCodeEnum.BIGGOD_ADD_EXCEPTION);
            }
        }
    }

    private SkillExaminePO checkSkillExamine(String skillExamineId){
        SkillExaminePO skillExaminePO = skillExamineMapper.get(Long.valueOf(skillExamineId));
        if(skillExaminePO == null){
            log.error("当前技能审核信息不存在!");
            throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_NOT_REPETITION);
        }
        return skillExaminePO;
    }

    private void checkExamine(String uid, Long categoryId) {
        if(categoryId == null){
            log.error("当前选择技能不存在!");
            throw new BaseBizException(ProcessCodeEnum.SKILL_NOT_EXIST);
        }
        SkillExaminePO skillExaminePOOld = skillExamineMapper.getByUidAndCategory(
                Long.valueOf(uid), categoryId);
        if(skillExaminePOOld != null){
            List<Long> ids = Collections.singletonList(skillExaminePOOld.getSkillExamineId());
            boolean flag = skillExamineMapper.remove(ids) > 0;
            if(!flag){
                log.error("删除已存在技能审核信息失败!");
                throw new BaseBizException(ProcessCodeEnum.SKILL_EXAMINE_REMOVE_EXCEPTION);
            }
        }
    }

    private void checkSkill(SkillExaminePO skillExaminePO) {
        SkillPO skillPOOld = skillMapper.getByUidAndCategory(skillExaminePO.getGodUid(), skillExaminePO.getCategoryId());
        if(skillPOOld != null){
            List<Long> ids = Collections.singletonList(skillPOOld.getSkillId());
            boolean flag = skillMapper.remove(ids) > 0;
            if(!flag){
                log.error("删除原技能信息失败!");
                throw new BaseBizException(ProcessCodeEnum.SKILL_REMOVE_EXCEPTION);
            }
        }
    }

    private Long getCategory(String categoryName){
        if(CategoryEnum.MLBB.getName().equals(categoryName)){
            return CategoryEnum.MLBB.getDefaultId();
        }else if(CategoryEnum.PUBG.getName().equals(categoryName)){
            return CategoryEnum.PUBG.getDefaultId();
        }else if(CategoryEnum.CHAT.getName().equals(categoryName)){
            return CategoryEnum.CHAT.getDefaultId();
        }
        return null;
    }
}
